import libc

#linkid mbedtls_base64_decode
fn mbedtls_base64_decode(anyptr dst, int dlen, rawptr<int> olen, anyptr src, int slen):i32

#linkid mbedtls_base64_encode
fn mbedtls_base64_encode(anyptr dst, int dlen, rawptr<int> olen, anyptr src, int slen):i32

fn encode([u8] src):[u8] {
    var max_len = ((src.len() + 2) / 3) * 4 + 1
    var dst = vec_new<u8>(0, max_len)
    int olen = 0

    mbedtls_base64_encode(dst.ref(), max_len, &olen, src.ref(), src.len())

    dst = dst.slice(0, olen)
    return dst
}

fn decode([u8] src):[u8]! {
    var max_len = (src.len() * 3) / 4 + 1
    var dst = vec_new<u8>(0, max_len)
    var olen = 0

    var ret = mbedtls_base64_decode(dst.ref(), max_len, &olen, src.ref(), src.len())
    if ret != 0 {
        throw errorf("base64 decode: invalid character in input")
    }

    dst = dst.slice(0, olen)
    return dst
}